<template>
  <div>
    <div class="top" style="margin-top: 60px">
      <div class="header">
        <a href="/" style="">
          <img src="~@/../public/logo.png" class="logo" style="width: 124px; height: 28px" alt="logo" />
          <span class="title">{{ $t(title) }}</span>
        </a>
      </div>
    </div>
    <div class="main">
      <div style="position: absolute; right: 20px; top: 20px; width: 130px">
        <a-select v-model="lang" @change="changeLang" style="width: 130px">
          <a-select-option v-for="(item, i) in langs" :key="i" :value="item.code">{{ item.name }}</a-select-option>
        </a-select>
      </div>
      <a-form-model class="user-layout-login" @keyup.enter.native="handleSubmit">
        <a-tabs
          :activeKey="customActiveKey"
          :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
          @change="handleTabClick"
        >
          <a-tab-pane key="tab1">
            <span slot="tab">
              <!-- <a-icon type="android" /> -->
              {{ $t('账号密码') }}
            </span>
            <login-account
              ref="alogin"
              @validateFail="validateFail"
              @success="requestSuccess"
              @fail="requestFailed"
              @loginDisabled="loginDisable"
            ></login-account>
            <a-form-model-item>
              <div style="display: flex; justify-content: space-between">
                <a-checkbox @change="handleRememberMeChange" :checked="rememberMe">{{ $t('记住账号') }}</a-checkbox>
                <a href="javascript:void(0);" @click="toSetPassword">{{ $t('忘记密码') }}</a>
              </div>
            </a-form-model-item>
            <a-form-model-item style="margin-top: 24px">
              <a-button
                size="large"
                type="primary"
                htmlType="submit"
                class="login-button"
                :loading="loadingBtn"
                @click.stop.prevent="handleSubmit"
                :disabled="loginBtn"
                >{{ $t('确定') }}
              </a-button>
            </a-form-model-item>
          </a-tab-pane>
          <a-tab-pane key="tab2">
            <span slot="tab">
              <!-- <a-icon type="android" /> -->
              {{ $t('l_微信扫码') }}
            </span>
            <i18n path="wx-login" tag="div" style="text-align: center">
              <a href="javascript:;" place="tips">{{ $t('微信扫一扫') }}</a>
            </i18n>
            <div style="margin: 40px auto; display: flex; justify-content: center; position: relative">
              <div id="qrcode" ref="qrcode" style="width: 100px; height: 100px"></div>
              <div
                v-if="isScan"
                style="
                  width: 100px;
                  height: 100px;
                  position: absolute;
                  left: 50%;
                  margin-left: -50px;
                  background-color: rgba(0, 0, 0, 0.9);
                "
              ></div>
              <div
                v-if="isScan"
                style="
                  width: 100px;
                  height: 100px;
                  position: absolute;
                  left: 50%;
                  margin-left: -50px;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                "
              >
                <div>
                  <div style="color: #fff">{{ $t('二维码失效') }}</div>
                  <div
                    @click="refreshQrcode"
                    style="
                      margin: 10px auto 0;
                      width: 60px;
                      height: 30px;
                      line-height: 30px;
                      color: #fff;
                      background-color: #1890ff;
                      border-radius: 26px;
                      text-align: center;
                      cursor: pointer
                    "
                  >
                    {{ $t('刷新') }}
                  </div>
                </div>
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>
      </a-form-model>
      <login-select-tenant ref="loginSelect" @success="loginSelectOk"></login-select-tenant>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import QRCode from 'qrcodejs2'
import { getAction } from '@/api/manage'
import {ACCESS_TOKEN, TENANT_ID} from '@/store/mutation-types'
import { timeFix } from '@/utils/util'
import LoginAccount from './LoginAccount'
import LoginSelectTenant from './LoginSelectTenant'
let random = ''

export default {
  components: {
    LoginSelectTenant,
    LoginAccount,
  },
  data() {
    return {
      title: '游乐场地营销专家系统',
      customActiveKey: 'tab1',
      rememberMe: false,
      loginBtn: true,
      loadingBtn: false,
      lang: localStorage.getItem('language'),
      langs: [],
      imgSrc: '',
      lockReconnect: false,
      isScan: false,
    }
  },
  async created() {
    Vue.ls.remove(ACCESS_TOKEN)
    var id = getQuery("id");
    console.log("UrlTanantID:"+id);
    if (id != null && id != undefined && id != "") {
      console.log("设置租户");
      sessionStorage.setItem("id", id);
      sessionStorage.setItem("TENANT_ID", id);
      Vue.ls.set(TENANT_ID,id)
    }
    else {
      console.log("清空租户！");
      sessionStorage.removeItem("id");
      sessionStorage.removeItem("TENANT_ID");
      Vue.ls.remove(TENANT_ID)
    }
    console.log("当前请求租户："+sessionStorage.getItem("id"));
    this.getRouterData()
    var hosturl = window.location.host
    if (hosturl.indexOf('.sp.') < 0 && hosturl.indexOf('127.0.0.1') < 0 && hosturl.indexOf('-sp.') < 0) {
      id = sessionStorage.getItem('id')
      var hosturl = window.location.host
      if (hosturl.indexOf('localhost') < 0 && hosturl.indexOf('192.168.') < 0) {
        if (id == '0' ||id == null || id == 'null') {
          this.$message.warn(this.$t('请确认登录地址'))
          this.loginBtn = true
          return
        }
        let res = await this.getShopInfo(id)
        if (res.code == 200 || res.code == 0) {
          if (res.result.records.length > 0) {
            if(res.result.records[0].state == 'N'){
              this.loginBtn = true
              this.$error({
                title: this.$t("提示"),
                content: res.result.records[0].name + this.$t("(未启用)"),
                okText: this.$t("确定"),
                onOk: () => {
                  return Promise.reject()
                },
              });
              return
            }else{
              this.title = res.result.records[0].name
              document.title = this.title
              localStorage.setItem('tenantName', this.title)
              Vue.ls.set('TENANT_ID', res.result.records[0].code, 7 * 24 * 60 * 60 * 1000)
              await this.getLanguage()
              this.loginBtn = false
            }
          }else{
            this.loginBtn = false
          }
        }else{
          this.loginBtn = false
        }
      } else if (id != null && id != 'null') {
        let res = await this.getShopInfo(id)
        if (res.code == 200 || res.code == 0) {
          if (res.result.records.length > 0) {
            if(res.result.records[0].state == 'N'){
              this.loginBtn = true
              this.$error({
                title: this.$t("提示"),
                content: res.result.records[0].name + this.$t("(未启用)"),
                okText: this.$t("确定"),
                onOk: () => {
                  return Promise.reject()
                },
              });
              return
            }else{
              this.title = res.result.records[0].name
              document.title = this.title
              localStorage.setItem('tenantName', this.title)
              Vue.ls.set('TENANT_ID', res.result.records[0].code, 7 * 24 * 60 * 60 * 1000)
              await this.getLanguage()
              this.loginBtn = false
            }
          }else{
            this.loginBtn = false
          }
        }else{
          this.loginBtn = false
        }
      } else {
        this.loginBtn = false
        await this.getLanguage()
      }
    } else {
      this.loginBtn = false
      await this.getLanguage()
    }
    let obj = JSON.parse(plugin.getData('C:\\ProgramData\\leyudm\\Manage\\user.json', 'remUser', localStorage.getItem('remUser'))) || {}
    this.rememberMe = obj.rememberMe || false
    let isChain = false
    getAction('/guest/system/isChain').then((res) => {
      if (res.success) {
        isChain = res.result.isChain
      }
      localStorage.setItem('isChain', isChain)
    })
  },
  methods: {
    getShopInfo(id){
      return new Promise(resolve=>{
        getAction('guest/shop/list', { code: id }).then((res) => {
          resolve(res)
        })
      })
    },
    getLanguage(){
      return new Promise(resolve=>{
        getAction('/guest/system/getLanguage').then((res) => {
          if (res.success) {
            this.langs = res.result
          }
          resolve()
        })
      })
    },
    refreshQrcode() {
      this.isScan=false
      this.getQrcode()
    },
    handleTabClick(key) {
      this.customActiveKey = key
      if (key == 'tab2') {
        this.isScan=false
        this.getQrcode()
      }
    },
    getQrcode() {
      let that=this
      random = Math.trunc((Math.random() + 1) * Math.pow(10, 9))
      that.initWebSocket()
      getAction('/guest/system/authQrCodeImg', {
        merchant: sessionStorage.getItem('id'),
        scene: 'wxlogin=1&random=' + random,
      }).then((res) => {
        if (res.success) {
          //this.imgSrc = res.result
          document.getElementById('qrcode').innerHTML = '' //获取生成二维码后显示的容器的ID
          that.qrCode = new QRCode('qrcode', {
            width: 100, //二维码的宽度
            height: 100, //二维码的高度
            text: res.result, //调用weixincode()方法时后台传的code
            colorDark: '#000', //二维码颜色
            colorLight: '#fff', //二维码底色
            title: '',
          })
          that.qrCode._el.title = ''
          let timer=null
          clearTimeout(timer)
          timer=setTimeout(function(){
            that.isScan=true
            that.$forceUpdate()
          },60000)
        }
      })
    },
    changeLang(e) {
      plugin.setLan(e, 'language')
      localStorage.setItem('language', e)
      this.$i18n.locale = e
      let tid=Vue.ls.get(TENANT_ID);
      if (tid)
      {
        if (window.location.href.indexOf("?")>0) {
          window.location.href = window.location.href + "&id=" + tid;
        }
        else {
          window.location.href = window.location.href + "?id=" + tid;
        }
      }
      else {
        window.location.reload()
      }
    },
    handleRememberMeChange(e) {
      this.rememberMe = e.target.checked
      localStorage.setItem('remUser', JSON.stringify({ rememberMe: this.rememberMe }))
      plugin.setData(
        'C:\\ProgramData\\leyudm\\Manage\\user.json',
        'remUser',
        JSON.stringify({ rememberMe: this.rememberMe })
      )
    },
    /**跳转到登录页面的参数-账号获取*/
    getRouterData() {
      this.$nextTick(() => {
        let temp = this.$route.params.username || this.$route.query.username || ''
        if (temp) {
          this.$refs.alogin.acceptUsername(temp)
        }
      })
    },
    //登录
    handleSubmit() {
      if (this.loginBtn) {
        return
      }
      this.loginBtn = true
      this.loadingBtn = true
      this.$refs.alogin.handleLogin(this.rememberMe)
    },
    // 校验失败
    validateFail() {
      this.loginBtn = false
      this.loadingBtn = false
    },
    // 登录后台成功
    async requestSuccess(loginResult) {
      localStorage.setItem('randomStr', loginResult.randomStr)
      this.$refs.loginSelect.show(loginResult)
    },
    //登录后台失败
    requestFailed(err) {
      let description = ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试'
      this.$notification['error']({
        message: this.$t('登录失败'),
        description: description,
        duration: 4,
      })
      this.loginBtn = false
      this.loadingBtn = false
    },
    loginSelectOk() {
      this.loginSuccess()
    },
    //登录成功
    loginSuccess() {
      this.$router.push({ name: 'dashboard' })
      this.$notification.success({
        message: this.$t('欢迎'),
        description: this.$t('welcome-back', { greetings: timeFix() }),
      })
    },
    loginDisable(bol) {
      this.loginBtn = bol
    },
    toSetPassword() {
      let that = this
      if (
        that.$refs.alogin.model.username === undefined ||
        that.$refs.alogin.model.username === '' ||
        that.$refs.alogin.model.username === null
      ) {
        that.$message.error(that.$t('请先输入要登录的账号'))
        return
      }
      getAction('/guest/user/isExist', {
        username: that.$refs.alogin.model.username,
      }).then((res) => {
        if (res.success) {
          that.$router.push({ name: 'alteration', params: { username: that.$refs.alogin.model.username } })
        } else {
          that.$message.error(res.message)
        }
      })
    },
    initWebSocket: function () {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var url =
        window._CONFIG['domianURL'].replace('https://', 'wss://').replace('http://', 'ws://') + 'websocket/' + random
      console.log(url)
      this.websock = new WebSocket(url)
      this.websock.onopen = this.websocketOnopen
      this.websock.onerror = this.websocketOnerror
      this.websock.onmessage = this.websocketOnmessage
      this.websock.onclose = this.websocketOnclose
    },
    websocketOnopen: function () {
      console.log('WebSocket连接成功')
      //心跳检测重置
      //this.heartCheck.reset().start();
    },
    websocketOnerror: function (e) {
      console.log('WebSocket连接发生错误')
      this.reconnect()
    },
    reconnect() {
      var that = this
      if (that.lockReconnect) return
      that.lockReconnect = true
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function () {
        console.info('尝试重连...')
        that.initWebSocket()
        that.lockReconnect = false
      }, 5000)
    },
    websocketOnmessage: function (e) {
      console.log('-----接收消息-------', e.data)
      var data = eval('(' + e.data + ')') //解析对象
      if (data.cmd == 'topic') {
        //扫码
        if (data.data.data.type == 'scan') {
          this.scan = '已扫码：' + data.data.data.topic
        }
        if (data.data.data.type == 'auth') {
          this.scan = '已授权：' + data.data.data.openId
          this.$refs.alogin.wxAuthLogin(data.data.data.openId, data.data.data.random)
        }
      }
      //心跳检测重置
      //this.heartCheck.reset().start();
    },
    websocketOnclose: function (e) {
      console.log('connection closed (' + e + ')')
      if (e) {
        console.log('connection closed (' + e.code + ')')
      }
      this.reconnect()
    },
    websocketSend(text) {
      // 数据发送
      try {
        this.websock.send(text)
      } catch (err) {
        console.log('send failed (' + err.code + ')')
      }
    },
  },
}
function getQuery(name) {
  var ScrStr = unescape(window.location.search.substr(1))
  ScrStr = ScrStr.substring(ScrStr.indexOf('?') + 1)
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  var r = ScrStr.match(reg)
  if (r != null) return unescape(r[2])
  return null
}
</script>
<style lang="less" scoped>
.top {
  text-align: center;

  .header {
    height: 44px;
    line-height: 44px;

    .badge {
      position: absolute;
      display: inline-block;
      line-height: 1;
      vertical-align: middle;
      margin-left: -12px;
      margin-top: -10px;
      opacity: 0.8;
    }

    .logo {
      vertical-align: sub;
      margin-right: 16px;
      border-style: none;
    }

    .title {
      font-size: 33px;
      color: rgba(0, 0, 0, 0.85);
      font-family: 'Chinese Quote', -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB',
        'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
        'Segoe UI Symbol';
      font-weight: 600;
      /* position: relative;
      top: 2px; */
    }
  }
}

.main {
  min-width: 260px;
  width: 368px;
  margin: 0 auto;
}

.footer {
  position: absolute;
  width: 100%;
  bottom: 0;
  padding: 0 16px;
  margin: 48px 0 24px;
  text-align: center;

  .links {
    margin-bottom: 8px;
    font-size: 14px;
    a {
      color: rgba(0, 0, 0, 0.45);
      transition: all 0.3s;
      &:not(:last-child) {
        margin-right: 40px;
      }
    }
  }
  .copyright {
    color: rgba(0, 0, 0, 0.45);
    font-size: 14px;
  }
}
.user-layout-login {
  label {
    font-size: 14px;
  }
  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
</style>
<style>
.valid-error .ant-select-selection__placeholder {
  color: #f5222d;
}
</style>